package jt.classic.app.dms.timer;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import jt.classic.app.dms.scanner.DMSFtpFileScanner;
import jt.classic.system.ISystem;
import jt.classic.system.user.IUser;
import jt.classic.system.user.UserManager;


/**
 * DMS 用户ftp上传文件扫描器
 *
 * @author mido
 *
 */
public class DMSFtpFolderTimer {
    private Timer timer = new Timer();
    private long delay = 10000;
    private long period = 20000;
    private File root;

    public DMSFtpFolderTimer(File folder) {
        this.root = folder;
    }

    public void runTask() {
        System.out.println(
            "system message: DMS ftp-folder timer task is running...");
        timer.schedule(new MyTask(this.root), this.delay, this.period);
    }

    public void stopTask() {
        System.out.println(
            "system message: DMS ftp-folder timer task is cancelled...");
        timer.cancel();
    }

    private class MyTask extends TimerTask {
        private File root;
        private DMSFtpFileScanner scanner;

        public MyTask(File folder) {
            this.root = folder;
            this.scanner = new DMSFtpFileScanner(null);
        }

        public void run() {
            if (this.root.exists() && this.root.isDirectory()) {
                File[] files = this.root.listFiles();

                if ((files != null) && (files.length > 0)) {
                    for (int i = 0; i < files.length; i++) {
                        if (files[i].isDirectory()) {
                            String logid = files[i].getAbsolutePath()
                                                   .substring(files[i].getAbsolutePath()
                                                                      .lastIndexOf(File.separator) +
                                    1);

                            UserManager manager = new UserManager();
                            IUser user = manager.getUserByLogID(logid);
                            manager.clean();

                            if ((user != null) &&
                                    !user.ilogid().equals("admin")) {
                                try {
                                    this.scanner.scanFtpFolder(files[i], user);
                                } catch (Exception ex) {
                                    ISystem.catchException(this, ex);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
